<template>
  <div class="mainsu">
    <div class="main_spac1">
      <div class="main_white padding10 paddingBottom20">
        <div class="main_crumbs boxdq">
          <div class="main_crumbs_l">
            <a href="javascript:;" @click="$router.back(-1)">
              <i class="el-icon-arrow-down"></i>返回
            </a>
            <em>|</em>
            <span>批量选择用户</span>
          </div>
        </div>
        <div class="mainor_form mg-t-15">
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="70px"
          >
            <el-form-item label="分组：" prop="group_id">
              <el-select
                v-model.trim="form.group_id"
                placeholder="分组"
                class="wid220"
              >
                <el-option
                  v-for="group in groupList"
                  :key="group.id"
                  :label="group.title"
                  :value="group.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用户：" prop="name">
              <el-input class="wid220" v-model="form.name" placeholder="请输入用户名称"></el-input>
            </el-form-item>
            <MainFormBtn
              @reset="reset(1)"
              @getSearchFor="getArticleList(1)"
              :loading="listLoading"
              :showBtn="false"
            />
          </el-form>
        </div>
        <div class="main-controls-wrap">
          <div class="mainor_te">
            <el-button @click="handleDels">批量删除</el-button>
            <el-button @click="changeUserDia">选择用户</el-button>
          </div>
        </div>
        <div class="main_table" style="min-height: 550px">
          <MainTable
            :loading="listLoading"
            :columns="userColumns"
            :tableData="list"
            :height="625"
            :enableHeaderDrag="false"
            @selection-change="handleSelectionChange"
          >
            <template #customLeft>
              <el-table-column width="80" type="selection" />
            </template>
            <el-table-column
              label="管理操作"
              prop="operate"
              width="220"
            >
              <template slot-scope="scope">
                <el-link type="danger" @click="handleDel(scope.row.id)">删除</el-link>
              </template>
            </el-table-column>
          </MainTable>
        </div>
        <div class="main_page boxdq">
          <div></div>
          <!-- 分页 -->
          <div class="main_page_r">
            <MainPagination
              :current-page="current.page"
              :page-sizes="[20, 30, 50, 100]"
              :page-size="current.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              background
              @size-change="changeSize($event, 1)"
              @current-change="changePage($event, 1)"
            />
          </div>
        </div>
      </div>

      <!-- 选择用户 -->
      <el-dialog
        title="选择用户"
        class="main_dialog dialog1000"
        :visible.sync="grantVisible"
        @closed="grantClose"
      >
        <div class="mainor_form">
          <el-form
            :inline="true"
            :model="grantForm"
            class="demo-form-inline"
            ref="grantRefForm"
            label-width="70px"
            style="width: 100%"
          >
            <el-form-item label="" prop="group_id">
              <el-select
                v-model.trim="grantForm.group_id"
                placeholder="分组"
                class="wid220"
              >
                <el-option
                  v-for="group in groupList"
                  :key="group.id"
                  :label="group.title"
                  :value="group.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="" prop="name">
              <el-input class="wid220" v-model="grantForm.name" placeholder="请输入用户名称"></el-input>
            </el-form-item>

            <el-form-item>
              <MainFormBtn
                @reset="reset(2)"
                @getSearchFor="getArticleList(2)"
                :loading="grantListLoading"
                :showBtn="false"
              />
            </el-form-item>
          </el-form>
        </div>
        <MainTable
          ref="addLabelTable"
          :loading="grantListLoading"
          :columns="grantColumns"
          :tableData="grantList"
          :height="400"
          :enableHeaderDrag="false"
          @select="grantSelect"
          @select-all="grantAllSelect"
        >
          <template #customLeft>
            <el-table-column width="80" type="selection" />
          </template>
          <el-table-column
            label="管理操作"
            prop="operate"
          >
            <template slot-scope="scope">
              <el-link type="danger" @click="handleBind(scope.row)">选择</el-link>
            </template>
          </el-table-column>
        </MainTable>
        <div class="main_page boxdq mg-b-16">
          <div></div>
          <!-- 分页 -->
          <div class="main_page_r">
            <MainPagination
              :current-page="grantCurrent.page"
              :page-sizes="[10, 15, 20, 100]"
              :page-size="grantCurrent.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="grantTotalCount"
              background
              @size-change="changeSize($event, 2)"
              @current-change="changePage($event, 2)"
            />
          </div>
        </div>
        <div slot="footer">
          <el-button class="marginLeft10" @click="grantClose">
            取 消
          </el-button>
          <el-button type="primary" @click="handleBatchBind" :disabled="batchAllBtn">
            确定
          </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getMemberList, addOrderLabelUser, delOrderLabelUser } from "@/api/order/orderLabel.js";
import { getUserGroup } from "@/api/currency.js";
import { orderLabelUser } from "./mockData.js"
import { packApi } from "@/utils/public";
export default {
  data() {
    return {
      ...orderLabelUser,
      id: this.$route.params.id,
      groupList: [], // 用户分组
      form: {
        group_id: "",
        name: "",
      },
      // 列表数据
      listLoading: false,
      list: [],
      // 分页
      current: {
        page: 1,
        pagesize: 20,
      },
      totalCount: 1,
      // 全选
      selectArr: [],
      // 弹窗
      grantVisible: false,
      grantSelectArr: [],
      grantForm: {
        group_id: "",
        name: "",
      },
      grantList: [],
      grantListLoading: false,
      grantCurrent: {
        page: 1,
        pagesize: 10,
      },
      grantTotalCount: 1,
    };
  },
  computed: {
    batchAllBtn() {
      return !this.grantSelectArr.length;
    },
  },
  created() {
    this.getGroup();
    this.getData();
  },
  methods: {
    // 获取用户分组
    getGroup() {
      getUserGroup(packApi()).then(res=> {
        this.groupList = res.data;
      });
    },
    // 获取列表
    getData() {
      this.listLoading = true;
      let data = packApi({
        label_id: this.id,
        ...this.current,
        ...this.form,
      });
      getMemberList(data).then(res=> {
        if(res.errcode == 0) {
          this.listLoading = false;
          this.list = res.data.list;
          this.totalCount = res.data.total;
        }
      })
    },
    // 获取选择用户列表
    getGrantData(isFirst = false) {
      this.grantListLoading = true;
      let data = packApi({
        label_id: this.id,
        ...this.grantCurrent,
        ...this.grantForm,
        label_func: 2,
      });
      getMemberList(data).then(res=> {
        this.grantListLoading = false;
        this.grantList = res.data.list;
        this.grantTotalCount = res.data.total;
        // 只有第一次打开才赋值
        if(isFirst) this.grantSelectArr = res.data.selected_user_ids;
        this.$nextTick(()=> {
          this.grantList.map(item=> {
            if(this.grantSelectArr.includes(item.id)) {
              this.$refs.addLabelTable.$refs.MainTable.toggleRowSelection(item, true);
            }
          });
        });
      });
    },
    // 搜索
    getArticleList(type) {
      switch (type) {
        case 1:
          this.current.page = 1;
          this.getData();
          break;
        case 2:
          this.grantCurrent.page = 1;
          this.getGrantData();
          break;
      }
    },
    // 重置
    reset(type) {
      switch (type) {
        case 1:
          this.$refs["userListFrom"].resetFields();
          this.getData();
          break;
        case 2:
          this.$refs["grantRefForm"].resetFields();
          this.getGrantData();
          break;
      }
    },
    // 分页
    changeSize(pageSize, type) {
      switch (type) {
        case 1:
          this.current.pagesize = pageSize;
          this.getData();
          break;
        case 2:
          this.grantCurrent.pagesize = pageSize;
          this.getGrantData();
          break;
      }
    },
    changePage(page, type) {
      switch (type) {
        case 1:
          this.current.page = page;
          this.getData();
          break;

        case 2:
          this.grantCurrent.page = page;
          this.getGrantData();
          break;
      }
    },
    // 选择分组
    changeUserDia() {
      this.getGrantData(true);
      this.grantVisible = true;
    },
    // 监听全选
    handleSelectionChange(val, type) {
      this.selectArr = val.map(item=> item.id);
    },
    // 表格选择事件
    grantSelect(selection, row) {
      if(this.grantSelectArr.includes(row.id)) {
        this.grantSelectArr = this.grantSelectArr.filter(e=> e != row.id);
      } else {
        this.grantSelectArr.push(row.id);
      }
    },
    // 表格全选事件
    grantAllSelect(selection) {
      const selectedIds = new Set(this.grantSelectArr);  // 使用 Set 来避免重复
      if(selection.length) {
        // 如果 selection 有长度，说明是全选
        this.grantList.forEach(item => {
          selectedIds.add(item.id);  // 添加选中的 ID
        });
      } else {
        // 如果 selection 长度为 0，说明是取消全选
        this.grantList.forEach(item => {
          selectedIds.delete(item.id);  // 删除所有选中的 ID
        });
      }
      // 更新 grantSelectArr 为新的选中项
      this.grantSelectArr = [...selectedIds];
    },
    // 批量选择按钮
    handleBatchBind() {
      // 后端会把没有传过去的id从列表删除 把列表id带过去
      let user_ids = this.grantSelectArr.join(",");
      let data = packApi({
        label_id: this.id,
        user_ids
      });
      addOrderLabelUser(data).then(res=> {
        if (res.errcode == 0) {
          this.$message.success("选择成功");
          this.grantClose();
          this.getData();
        } else {
          this.$message.error(res.errmsg);
        }
      })
    },
    // 单个选择
    handleBind(row) {
      this.$refs.addLabelTable.$refs.MainTable.toggleRowSelection(row, true);
      this.grantSelect(null, row);
    },
    // 关闭弹窗
    grantClose() {
      this.grantForm.group_id = "";
      this.grantForm.name = "";
      this.grantCurrent.page = 1;
      this.grantCurrent.pagesize = 10;
      this.grantList = [];
      this.grantSelectArr = [];
      this.grantVisible = false;
    },
    // 删除
    handleDel(id) {
      this.$confirm("是否将该用户从当前列表中删除？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let data = packApi({
          label_id: this.id,
          user_ids: id,
        });
        delOrderLabelUser(data).then((res) => {
          if (res.errcode == 0) {
            this.$message.success("删除成功");
            this.getData();
          } else {
            this.$message.error(res.errmsg);
          }
        });
      });
    },
    // 批量删除
    handleDels() {
      if (this.selectArr.length) {
        this.$confirm(`你已经选择【${this.selectArr.length}】个用户，是否删除？`, "提示",
          {
            confirmButtonText: "确定",
            type: "warning",
          }
        ).then(() => {
          let user_ids = this.selectArr.join(",");
          let data = packApi({
            label_id: this.id,
            user_ids
          });
          delOrderLabelUser(data).then(res => {
            if (res.errcode == 0) {
              this.$message.success("删除成功");
              this.getData();
            } else {
              this.$message.error(res.errmsg);
            }
          });
        });
      } else {
        this.$message.warning("请选择用户");
      }
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";
/deep/.main_dialog .el-checkbox {
  margin-bottom: 0;
}
.mg-t-15 {
  margin-top: 15px;
}
.mainsu {
  .mainor_form form {
    width: calc(100% - 120px);
    .el-form-item {
      margin-bottom: 10px;
    }
  }
}
// 导出订单表头
.exptitle {
  display: block;
  font-size: 16px;
  color: #000000;
  margin: 0 0 10px;
}
.company_name {
  padding-top: 15px;
}
.maintip {
  text-align: center;
  padding-top: 15px;
  font-size: 18px;
  span {
    display: inline;
    padding: 18px 0;
    color: red;
  }
}
.new_navbar_svg {
  vertical-align: top;
  margin-left: 5px;
  use {
    fill: #ffffff;
  }
}
.status0 {
  color: red;
}
.status1 {
  color: #118ab2;
}
.status2 {
  color: #03a98e;
}
/deep/.el-dialog__body {
  padding-bottom: 0;
}

/deep/ .main_table .el-table--small td .cell {
  height: 40px !important;
  line-height: 40px !important;
}
.error-message {
  color: red;
  position: absolute;
  bottom: -12px;
}
/deep/.is-invalid .el-input__inner {
  border-color: red;
}
</style>
